﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for ProductionOrder.xaml
    /// </summary>
    public partial class YCAAV25 : DocumentBase
    {
        #region-------------Properties-----------------------
        ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        INTEXDBC INTEXDBC
        {
            get
            {
                return app.INTEXDBC;
            }
        }
        INTEXBL INTEXBL
        {
            get
            {
                return app.INTEXBL;
            }
        }
        bool isconfirmed = false;
        bool IsLoaded = false;
        DataRow LastRow = null;
        DataSet SetMap = null; 
        YCAAV25Data m_Data; 
        DataTable tbUser = null;
        bool IsSaved = false; 
        public string LO
        {
            get
            {
                return txtLO.Text;
            }
        }
        public string LB
        {
            get
            {
                return txtLB.Text;
            }
        }
        public string LP
        {
            get
            {
                return txtLP.Text;
            }
        }
        BindingListCollectionView cvPMAT
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgPMAT.ItemsSource);
            }
        }
        public SETINTEXDB SetEnv
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetEnv");
            }
        }
        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData");
            }
        }
        public SETINTEXDB SetProd
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetProd");
            }
        }
        string user = "";
        #endregion
        public YCAAV25()
        {
            InitializeComponent();
            this.Name = "生产入库";
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {  
            tbUser = (DataTable)dicParamater["USERRIGHT"];
            user = (string)dicParamater["User"];
            m_Data = new YCAAV25Data();
            m_Data.UserID = user;
            ReSetEnv();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (IsLoaded)
                    return;
                IsLoaded = true;
                vwABPOSMAT.View.CurrentChanged += vwABPOSMAT_CurrentChanged;
                txtABPART.Text = "25310010684";
                EventDispatcher.Instance.OnMessage += new EventHandler<MessageEventArgs>(_LogExplorerDock.OnMessage);
                RefreshFile();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;
        }

        void vwABPOSMAT_CurrentChanged(object sender, EventArgs e)
        {
            if (dwABPOSMAT == null)
                return;
            DataSet SResult = m_Data.LoadData(dwABPOSMAT);
            SetProd.Clear();
            SetProd.Merge(SResult);
            FilterWD();
            FilterFD();
            chkS.IsChecked = false;
            chkM.IsChecked = false;
            chkL.IsChecked = false;
            chkXL.IsChecked = false;
        }
        public void ReSetEnv()
        {
            DataSet setResult = new DataSet();
            try
            {
                setResult = m_Data.LoadEnv();
                SetEnv.Clear();
                SetEnv.Merge(setResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        #region=====vwABPOS=======
        CollectionViewSource vwABPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwABPOS");
            }
        }
        DataRow dwABPOS
        {
            get
            {
                if (vwABPOS.View == null)
                    return null;
                if (SetData.ABPOS.Rows.Count == 0)
                    return null;
                if ((DataRowView)vwABPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwABPOS.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwABPOSMAT=======
        CollectionViewSource vwABPOSMAT
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwABPOSMAT");
            }
        }
        DataRow dwABPOSMAT
        {
            get
            {
                if (vwABPOSMAT.View == null)
                    return null;
                if (SetData.ICC_ABPOS_MAT.Rows.Count == 0)
                    return null;
                if ((DataRowView)vwABPOSMAT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwABPOSMAT.View.CurrentItem).Row;
            }
        }
        #endregion
        #region
        BindingListCollectionView cvWDECK
        {
            get
            {
               return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgWDECK.ItemsSource);
            }
        }
        BindingListCollectionView cvFDECK
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgFDECK.ItemsSource);
            }
        } 
        #endregion

        #region=====vwABPAUF=======
        CollectionViewSource vwABPAUF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwABPAUF");
            }
        }
        DataRow dwABPAUF
        {
            get
            {
                if (vwABPAUF.View == null)
                    return null;
                if ((DataRowView)vwABPAUF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwABPAUF.View.CurrentItem).Row;
            }
        }
        #endregion

        #region=====vwLIEFDAT=======
        CollectionViewSource vwLIEFDAT
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwLIEFDAT");
            }
        }
        DataRow dwLIEFDAT
        {
            get
            {
                if (vwLIEFDAT.View == null)
                    return null;
                if ((DataRowView)vwLIEFDAT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwLIEFDAT.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwFSSTAMM=======
        CollectionViewSource vwFSSTAMM
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwFSSTAMM");
            }
        }
        DataRow dwFSSTAMM
        {
            get
            {
                if (vwFSSTAMM.View == null)
                    return null;
                if ((DataRowView)vwFSSTAMM.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwFSSTAMM.View.CurrentItem).Row;
            }
        }
        #endregion

        private void FilterWD()
        {
            string filter = "WDAUFKRS='" + dwABPOSMAT["KRS"].ToString() + "' AND WDAUFLFD ='" + dwABPOSMAT["LFD"].ToString() + "' AND ABPFARBE='" + dwABPOSMAT["ABPFARBE"].ToString()+"'";
            cvWDECK.CustomFilter = filter; 
        }
        private void FilterFD()
        {
            string filter = "FDAUFKRS='" + dwABPOSMAT["KRS"].ToString() + "' AND FDAUFLFD='" + dwABPOSMAT["LFD"].ToString() + "' AND ABPFARBE='" + dwABPOSMAT["ABPFARBE"].ToString() + "'";
            cvFDECK.CustomFilter = filter; 
        }
        private void cmdLoad_Click(object sender, RoutedEventArgs e)
        {
            DataSet SResult = null;
            try
            {
                DataRow dwData = SetData.ABPOS.NewRow();
                dwData["ABPMANDANT"] = app.Mandant;
                dwData["ABPART"] = txtABPART.Text.ToString().Trim();
                SResult = m_Data.ABPLoad(dwData);
                SetData.Clear();
                SetData.Merge(SResult);
                SetProd.Merge(SResult);
                SetProd.Clear();
                if (vwABPAUF.View != null)
                {
                    vwABPAUF.View.MoveCurrentToFirst();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void ABP_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dwABPAUF == null)
                return;
            txtKRS.Text=dwABPAUF["ABPAUFKRS"].ToString();
            txtLFD.Text = dwABPAUF["ABPAUFLFD"].ToString();
            DataSet SResult = m_Data.LoadABPOS(dwABPAUF);
            SetData.ABPOS.Clear();
            SetData.ICC_ABPOS_MAT.Clear();
            SetData.Merge(SResult);
            if (vwABPOSMAT.View != null)
            {
                vwABPOSMAT.View.MoveCurrentToFirst();
            }
            foreach (DataRow rx in SetData.ABFOLGE)
            {
                if (rx["ABFLIEFNR"].ToString() == "00000000" || rx["ABFLO"].ToString() == "  ")
                {
                    MessageBox.Show("外发厂需要指定，请联系电脑部或计划部，指定外发厂!");
                    break;
                }
            }
        }
        private void cmdLoadAB_Click(object sender, RoutedEventArgs e)
        {
            DataRow dwABPOS = m_Data.INTEXDB.ABPOS.NewRow();
            dwABPOS["ABPMANDANT"] = "00";
            dwABPOS["ABPAUFKRS"] = txtKRS.Text;
            dwABPOS["ABPAUFLFD"] = Helpers.Helper.Right("000000"+txtLFD.Text,6);
            DataSet SResult = m_Data.LoadABPOS(dwABPOS);
            SetData.ABPOS.Clear();
            SetData.ICC_ABPOS_MAT.Clear();
            SetData.Merge(SResult);
            if (vwABPOSMAT.View != null)
            {
                vwABPOSMAT.View.MoveCurrentToFirst();
            }
            foreach (DataRow rx in SetData.ABFOLGE)
            {
                if (rx["ABFLIEFNR"].ToString() == "00000000" || rx["ABFLO"].ToString() == "  ")
                {
                    MessageBox.Show("外发厂需要指定，请联系电脑部或计划部，指定外发厂!");
                    break;
                }
            }
        }
        private void RefreshFile()
        {
            int count = 0;
            list01.Items.Clear();
            list02.Items.Clear();
            string filestemp = @"C:\IntexReport\Data\YCAAV25\01Temp";
            string[] files = System.IO.Directory.GetFiles(filestemp);
            foreach (string file in files)
            {
                list01.Items.Add(file.Replace(filestemp + "\\", ""));
                count++;
            }
            filestemp = @"C:\IntexReport\Data\YCAAV25\02Incoming";
            files = System.IO.Directory.GetFiles(filestemp);
            foreach (string file in files)
            {
                list02.Items.Add(file.Replace(filestemp + "\\", ""));
                count++;
            }
            if (count > 0)
            {
                SetProd.Clear();
                SetProd.Merge(SetData.ABPOS);
                m_Data.AB2FB(SetProd);
            }
        }


        private void cmdLoadExisting_Click(object sender, RoutedEventArgs e)
        {
            DataSet SResult = m_Data.LoadExisting();
          
            SetData.ABPOS.Clear();
            SetData.ICC_ABPOS_MAT.Clear();
            SetData.Merge(SResult);
            if (vwABPOSMAT.View != null)
            {
                vwABPOSMAT.View.MoveCurrentToFirst();
            }
        }
        private void cmdRemove_Click(object sender, RoutedEventArgs e)
        {
            if (dwABPOSMAT == null)
                return;
            if (txtDFlag.Text == "N")
            {
                MessageBox.Show("请手工将删除标志设置为Y");
                return;
            }
            txtDFlag.Text = "N";
            string KRS = dwABPOSMAT["KRS"].ToString();
            string LFD = dwABPOSMAT["LFD"].ToString();
            string ABPART = dwABPOSMAT["ABPART"].ToString();
            string ABPFARBE = dwABPOSMAT["ABPFARBE"].ToString();
            var query = from DataRow row in SetData.ABPOS.AsEnumerable()
                        where row["ABPAUFKRS"].ToString() == KRS
                        && row["ABPAUFLFD"].ToString() == LFD
                        && row["ABPART"].ToString() == ABPART
                        && row["ABPFARBE"].ToString() == ABPFARBE
                        select row;
            foreach (DataRow row in query)
            {
                INTEXDBC.DeleteICC_ABPOS_EXT(row, 1);
            }
        } 
        private void cmdSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SetProd.Clear();

                foreach (DataRow row in SetData.ABPOS.Rows)
                {
                    row["ABPZLO"] = LO;
                    row["ABPZLB"] = LB;
                    row["ABPVFAUFLFD"] = LP;
                    row["ABPAENDBEN"] = m_Data.UserID;
                    row["ABPAENDDAT"] = m_Data.date;
                    if (dwFSSTAMM != null)
                    {
                        row["ABPKPROGRP"] = dwFSSTAMM["FSPROGRP"];
                        row["ABPKARTGRP"] = dwFSSTAMM["FSARTGRP"];
                    }
                    row["ABPFILLER1"] = System.Guid.NewGuid().ToString();
                    INTEXDBC.SaveICC_ABPOS_EXT(row);
                }               
                SetData.ABPOS.Clear();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void cmdRepairWB_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SetProd.Clear();
                string color = dwABPOSMAT["ABPFARBE"].ToString();
                foreach (DataRow row in SetData.ABPOS.Rows)
                {
                    /*if (row["ABPFARBE"].ToString() != color)
                        continue;*/
                    row["ABPAUFART"] = "RP";//修补面料未消耗的情况
                    row["ABPEAKG"] = row["ABPEASTK"];
                    row["ABPZLO"] = LO;
                    row["ABPZLB"] = LB;
                    row["ABPVFAUFLFD"] = LP;
                    row["ABPAENDBEN"] = m_Data.UserID;
                    row["ABPAENDDAT"] = m_Data.date;
                    if (dwFSSTAMM != null)
                    {
                        row["ABPKPROGRP"] = dwFSSTAMM["FSPROGRP"];
                        row["ABPKARTGRP"] = dwFSSTAMM["FSARTGRP"];
                    }
                    row["ABPFILLER1"] = System.Guid.NewGuid().ToString();
                    INTEXDBC.SaveICC_ABPOS_EXT(row);
                }               
                SetData.ABPOS.Clear();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
      
        private void cmdNewEntry_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SetProd.Clear();
                string KRS = dwABPOSMAT["KRS"].ToString();
                string LFD = dwABPOSMAT["LFD"].ToString();
                string ABPART = dwABPOSMAT["ABPART"].ToString();
                string ABPFARBE = dwABPOSMAT["ABPFARBE"].ToString();
                string filter = "ABPAUFKRS='" + KRS + "' AND ABPAUFLFD='" + LFD + "' AND ABPART='" + ABPART + "' AND ABPFARBE='" + ABPFARBE + "'";
                DataRow[] rows = SetData.ABPOS.Select(filter);
                DataTable tb;
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "ABPOS";
                    SetProd.Clear();
                    SetProd.Merge(tb);
                }
                else
                    return;

                foreach (DataRow row in SetProd.ABPOS.Rows)
                {
                    if (row["ABPAUFKRS"].ToString() + row["ABPAUFLFD"].ToString() != KRS + LFD)
                        continue;
                    row["ABPZLO"] = LO;
                    row["ABPZLB"] = LB;
                    row["ABPVFAUFLFD"] = LP;
                    row["ABPAENDBEN"] = m_Data.UserID;
                    row["ABPAENDDAT"] = m_Data.date;
                    if (dwFSSTAMM != null)
                    {
                        row["ABPKPROGRP"] = dwFSSTAMM["FSPROGRP"];
                        row["ABPKARTGRP"] = dwFSSTAMM["FSARTGRP"];
                    }
                    decimal ABPSOLLMENGE7 = System.Convert.ToDecimal(row["ABPSOLLMENGE7"].ToString());
                    decimal ABPEALFM = System.Convert.ToDecimal(row["ABPEALFM"].ToString());
                    decimal ABPEAKG = System.Convert.ToDecimal(row["ABPEAKG"].ToString());
                    string ABPERLKZ = row["ABPERLKZ"].ToString();
                    string Color = row["ABPFARBE"].ToString();
                    string Size = row["ABPGROE"].ToString();
                    if (row["ABPAUFART"].ToString() != "RP")
                        //&& row["ABPAUFART"].ToString() != "RF")
                    {
                        if (ABPERLKZ == " ")
                        {
                            if (ABPSOLLMENGE7 - ABPEALFM - ABPEAKG * 100 <= 0)
                            {
                                if (MessageBox.Show("本SKU:" + Color + "-" + Size + " 计划数量"
                                    + ABPSOLLMENGE7 / 100 + "已经接收:"
                                    + ABPEALFM / 100 + "+" + ABPEAKG
                                    + "已经达到，确认则完结此单", "请确认!", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                                {
                                    row["ABPERLKZ"] = "J";
                                    row["ABPERLDAT"] = m_Data.date;
                                }
                            }
                        }
                        else
                        {
                            if (row["ABPERLDAT"].ToString().Trim() == "0")
                            {
                                row["ABPERLDAT"] = m_Data.date;
                            }
                        }
                        if (row["ABPFILLER1"].ToString().Trim() == "")
                        {
                            row["ABPFILLER1"] = System.Guid.NewGuid().ToString();
                        }
                    }
                }  
                m_Data.AB2FB(SetProd);
                if (vwABPOSMAT != null)
                {
                    vwABPOSMAT.View.MoveCurrentTo(-1);
                }                
                filter="KRS='"+KRS+"' AND LFD='"+LFD+"' AND ABPART='"+ABPART+"' AND ABPFARBE='"+ABPFARBE+"'";
                //ICC_ABPOS_MAT
                rows=SetData.ICC_ABPOS_MAT.Select(filter);
                foreach (DataRow row in rows)
                {
                    row.Delete();
                }
                SetData.AcceptChanges();
                //SetData.ABPOS.Clear();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void txtABPART_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                cmdLoad_Click(null, null);
            }
        }
        private void Confirm(object sender)
        {
            if (isconfirmed)
                return;
            TextBox Sender = sender as TextBox;
            if (dwABPOSMAT == null)
                return;
            string color = dwABPOSMAT["ABPFARBE"].ToString();
            string size = "S      ";
            string QTY = Sender.Text;
            if (QTY.Trim() == "")
            {
                return;
            }
            if (QTY == "0")
            {
                return;
            }
            switch (Sender.Name)
            {
                case "txtQtyS":
                    size = "S      "; 
                    break;
                case "txtQtyM":
                    size = "M      "; 
                    break;
                case "txtQtyL":
                    size = "L      "; 
                    break;
                case "txtQtyXL":
                    size = "XL     ";
                    break;
            }
            CheckBox chk = this.FindName("chk" + size.Trim()) as CheckBox;
            if (chk.IsChecked == true)
                return;
            var Query = from DataRow row in SetData.ABPOS.AsEnumerable()
                        where row["ABPGROE"].ToString() == size
                        && row["ABPFARBE"].ToString() == color
                        select row;
            if (Query.Count() == 0)
            {
                MessageBox.Show(size + "没有对应生产单!");
            }
            decimal QtyR = Convert.ToDecimal(dwABPOSMAT[size.Trim()].ToString());
            decimal QtyP = Convert.ToDecimal(dwABPOSMAT[size.Trim() + "P"].ToString());
            if (QtyP - (QtyR + Convert.ToDecimal(QTY)) <= 0)
            {
                if (QtyR == 0)
                {
                    chk.IsChecked = true;
                }
                else
                {
                    if (MessageBox.Show("本生产单数量已经达到，确认继续入库?", "请确认", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    {
                        return;
                    }
                }
                chk.IsChecked = true;
            }
            foreach (DataRow row in Query)
            {
                row["ABPEAKG"] = QTY;
                if (chk.IsChecked==true)
                {
                    row["ABPERLKZ"] = "J";
                    row["ABPERLDAT"] = m_Data.date;
                }
            }
        }
        private void txtQty_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key != System.Windows.Input.Key.Enter)
                return;
            Confirm(sender);
            isconfirmed = true;
            TextBox Sender = sender as TextBox;
            switch (Sender.Name)
            {
                case "txtQtyS": 
                    //txtQtyM.Focus();
                    break;
                case "txtQtyM": 
                    //txtQtyL.Focus();
                    break;
                case "txtQtyL": 
                    //txtQtyXL.Focus();
                    break;
                case "txtQtyXL": 
                    break;
            } 
        }
        private void ValicateCheck(string size)
        {
            if (dwABPOSMAT == null)
                return;
            CheckBox chk = this.FindName("chk" + size.Trim()) as CheckBox;
            if (chk.IsChecked == true)
                return;
            decimal QtyY = Convert.ToDecimal(dwABPOSMAT[size.Trim()+"Y"].ToString());
            decimal QtyR = Convert.ToDecimal(dwABPOSMAT[size.Trim()].ToString());
            decimal QtyP = Convert.ToDecimal(dwABPOSMAT[size.Trim() + "P"].ToString());
            if (QtyP - (QtyR + Convert.ToDecimal(QtyY)) <= 0)
            { 
                //chk.IsChecked = true;
            }
            chk.IsChecked = false;
        }
        private void txtQty_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox Sender = sender as TextBox;
            Sender.SelectAll();
            isconfirmed = false;
            string size = "S";
            switch (Sender.Name)
            {
                case "txtQtyS":
                    size = "S      "; 
                    break;
                case "txtQtyM":
                    size = "M      "; 
                    break;
                case "txtQtyL":
                    size = "L      "; 
                    break;
                case "txtQtyXL":
                    size = "XL     "; 
                    break;
            }
            ValicateCheck(size);
        }

        private void txtQty_LostFocus(object sender, RoutedEventArgs e)
        {            
            Confirm(sender);
            isconfirmed = true;
        }

        private void chkXL_Checked(object sender, RoutedEventArgs e)
        {

        }

      
        private void btnFilter_Click(object sender, RoutedEventArgs e)
        {
            string filter="LFD='" + Helpers.Helper.Right("000000" + PLFD.Text.ToString(), 6)+"'";
            cvPMAT.CustomFilter = filter;
        }

        private void btnFilterClear_Click(object sender, RoutedEventArgs e)
        {
            cvPMAT.CustomFilter = null;
        }
    }
}
